//
//  RHPdfFileVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/8/7.
//

#import "RHPdfFileVC.h"
#import "RHPdfFileModel.h"
#import "RHPdfFileCell.h"

@interface RHPdfFileVC ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic ,strong) UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *fileArr;
@end

@implementation RHPdfFileVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"Select File";
    [self getPdfFile];
    [self setupUI];
}
-(void)getPdfFile
{
    _fileArr = [NSMutableArray array];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    NSString *inboxPath = [NSString stringWithFormat:@"%@/Inbox",docDir];
    if([[NSFileManager defaultManager]fileExistsAtPath:inboxPath]){
        NSError *error;
        NSArray  *arr = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:inboxPath error:&error];
        if(error){
            NSLog(@"--->打开文件错误:%@",error);
        }else{
            for (NSString *name in arr) {
                NSLog(@"---->文件名:%@",name);
                if([name hasSuffix:@".pdf"]||[name hasSuffix:@".doc"]||[name hasSuffix:@".docx"]||[name hasSuffix:@".zip"]||[name hasSuffix:@".rar"]){
                    RHPdfFileModel *model = [[RHPdfFileModel alloc]init];
                    model.fileName = name;
                    NSString *fileName = [NSString stringWithFormat:@"%@/%@",inboxPath,name];
                    model.filePath = fileName;
                    NSError *fileError;
                    NSDictionary *fileAttributes =[[NSFileManager defaultManager] attributesOfItemAtPath:fileName error:&fileError];
                    if(!fileError){
                        NSLog(@"---->文件属性:%@",fileAttributes);
                        NSInteger size = [fileAttributes[NSFileSize] integerValue];
                        model.size = size;
                        
                        CGFloat fileSize = size;
                        NSString *uint = @"b";
                        if(size >1024){
                            uint = @"Kb";
                            fileSize = size / 1024.0;
                        }
                        if(size > 1024*1024){
                            uint = @"M";
                            fileSize = size / 1024.0/1024.0;
                        }
                        model.fileSize = [NSString stringWithFormat:@"%.2f%@",fileSize,uint];
                        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
                        NSString *createDate = [formatter stringFromDate:fileAttributes[NSFileModificationDate]];
                        model.createTime = createDate;
                        
                    }
                    [_fileArr addObject:model];
                    [self.tableView reloadData];
                    NSLog(@"---model:%@",model.yy_modelDescription);
                }
                
            }
        }
    }else{
        NSError *error;
        BOOL result = [[NSFileManager defaultManager]createDirectoryAtPath:inboxPath withIntermediateDirectories:YES attributes:nil error:&error];
        if(result){
            NSLog(@"------>创建文件夹成功");
        }else{
            NSLog(@"------>创建文件夹失败");
        }
        
    }
    
    [_tableView setNoDataType:NoData typeDes:self.fileArr.count>0?@"no file, please import a file":@""];
    
}


-(void)setupUI{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getPdfFile) name:@"PdfFileUpdate" object:nil];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setSeparatorColor:UIColor.clearColor];
    _tableView.estimatedRowHeight = 500;
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHPdfFileCell class] forCellReuseIdentifier:@"RHPdfFileCell"];
    [self.view addSubview:_tableView];
    
   
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.fileArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  
    RHPdfFileCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHPdfFileCell"];
    
    
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    RHPdfFileModel *model = self.fileArr[indexPath.row];
    cell.model = model;
    
    MGSwipeButton *oneBtn = [MGSwipeButton buttonWithTitle:@"删除".rh_localized icon:[UIImage imageNamed:@"reset_password"] backgroundColor:FontColor(@"#3ECE80") padding:18 callback:^BOOL(MGSwipeTableCell * _Nonnull cell) {
        
        if([[NSFileManager defaultManager]fileExistsAtPath:model.filePath]){
            NSError *error;
            [[NSFileManager defaultManager]removeItemAtPath:model.filePath error:&error];
            if(!error){
                NSLog(@"删除成功");
                [self getPdfFile];
            }else{
                NSLog(@"删除失败");
            }
        }
        return YES;
    }];
    cell.rightButtons = @[oneBtn];
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    RHPdfFileModel *fileModel = self.fileArr[indexPath.row];
    if(fileModel.size > 1024*1024*20){
        [QMUITips showError:@"The file size cannot exceed 20M"];
        return;
    }
    if(self.selectBlock){
        self.selectBlock(self.idx,self.fileArr[indexPath.row]);
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
